const db = require('../model/db')
const Base = require('./base')

const TableName = 'tk_message'

class Message extends Base {
  // 列表
  async findAll(req, res) {
    const { content, page = 1, limit = 10 } = req.query
    const startIndex = (page - 1) * limit

    const app_id = req.headers.appid || 1
    const data = { total: 0, rows: [] }
    const sql1 = `select * from ${TableName} where app_id = ${app_id} and content LIKE ? order by id desc LIMIT ?, ?`
    const sql2 = `select count(*) as total from ${TableName} where content LIKE ? and app_id = ${app_id}`

    const [rows] = await db.query(sql1, [`%${content || ''}%`, startIndex, Number(limit)])
    const [[{ total }]] = await db.query(sql2, [`%${content || ''}%`])

    if (rows.length > 0) {
      data.rows = rows
      data.total = total
    }

    return res.cc('success', 0, { data })
  }

  async findOne(req, res) {
    await this.baseFindOne({ req, res })
  }

  // 新增
  async create(req, res) {
    // const { verify } = req.body
    const sql = `insert into ${TableName} set ?`
    const app_id = req.headers.appid || 1

    // console.log('verify', verify)
    // console.log('req.session', req.session)
    // console.log('req.session.verify', req.session.verify)
    // console.log('req.cookies', req.cookies)

    // if (verify !== req.session.verify) {
    //   return res.cc('验证码不正确', 1)
    // }

    delete req.session.verify

    req.body.app_id = app_id

    const [rows] = await db.query(sql, [req.body])

    if (!rows.affectedRows) {
      return res.cc('新增失败！')
    }

    return res.cc('success', 0)
  }

  async update(req, res) {
    await this.baseUpdate(req, res)
  }

  async remove(req, res) {
    await this.baseRemove(req, res)
  }
}

module.exports = Message
